package com.liaozibo.demo.seckill.support.service.impl;

import com.liaozibo.demo.seckill.support.common.exception.BizException;
import com.liaozibo.demo.seckill.support.dao.mapper.ActivityMapper;
import com.liaozibo.demo.seckill.support.dao.mapper.OrderMapper;
import com.liaozibo.demo.seckill.support.dao.model.ActivityDO;
import com.liaozibo.demo.seckill.support.dao.model.OrderDO;
import com.liaozibo.demo.seckill.support.export.dto.OrderDTO;
import com.liaozibo.demo.seckill.support.service.SettlementService;
import com.liaozibo.demo.seckill.support.util.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class SettlementServiceImpl implements SettlementService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Override
    @Transactional
    public void submitOrder(OrderDTO orderDTO) {
        Long result = redisUtils.decrStock(orderDTO.getCode(), orderDTO.getBuyNum());
        if (Objects.equals(result, 0L)) {
            // 扣减失败
            throw new BizException("抢购失败");
        }
        ActivityDO activityDO = activityMapper.selectByCode(orderDTO.getCode());
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(orderDTO, orderDO);
        orderMapper.insert(orderDO);
        activityMapper.updateStock(activityDO.getId(), orderDO.getBuyNum());
    }
}
